﻿/******************************************************************************
 * 
 * Announce: CSharpKit, Basic algorithms, components and definitions.
 *           Copyright (C) ShenYongchen.
 *           All rights reserved.
 *   Author: 申永辰.郑州 (shenyczz@163.com)
 *  WebSite: http://github.com/shenyczz/CSharpKit
 *
 * THIS CODE IS LICENSED UNDER THE MIT LICENSE (MIT).
 * THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF 
 * ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
 * IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
 * PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
 * 
******************************************************************************/

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;

namespace CSharpKit.Numerics.LinearAlgebra
{
    public interface IVectorStorage : IStorage { }

    /// <summary>
    /// 矢量存储器
    /// </summary>
    /// <typeparam name="T"></typeparam>
    [Serializable]
    public abstract partial class VectorStorage<T> : Numeric<T>, IVectorStorage, IEquatable<VectorStorage<T>>
        where T : struct, IFormattable, IEquatable<T>
    {
        #region Constructors

        public VectorStorage(int length)
        {
            if (length <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(length), Resources.Numerics.ArgumentMustBePositive);
            }

            Length = length;

            _IsDense = false;
        }

        #endregion


        #region Length

        [DataMember(Order = 1)]
        public int Length { get; private set; }

        #endregion

        #region IsDense

        protected bool _IsDense;
        /// <summary>
        /// 是否密集
        /// </summary>
        public bool IsDense => _IsDense;

        #endregion


        #region Indexer - 索引器

        public T this[int index]
        {
            get
            {
                ValidateRange(index);
                return At(index);
            }

            set
            {
                ValidateRange(index);
                At(index, value);
            }
        }

        internal abstract T At(int index);
        internal abstract void At(int index, T tvalue);

        #endregion


        #region IEquatable<VectorStorage<T>>

        public override bool Equals(object obj)
        {
            return Equals(obj as VectorStorage<T>);
        }

        public virtual bool Equals(VectorStorage<T> other)
        {
            if (other == null)
            {
                return false;
            }

            if (Length != other.Length)
            {
                return false;
            }

            // 参考地址相同即同一个对象
            if (ReferenceEquals(this, other))
            {
                return true;
            }

            for (var index = 0; index < Length; index++)
            {
                if (!At(index).Equals(other.At(index)))
                {
                    return false;
                }
            }

            return true;
        }

        public override int GetHashCode()
        {
            int hash = 17;
            var hashNum = System.Math.Min(Length, 25);

            unchecked
            {
                for (var i = 0; i < hashNum; i++)
                {
                    hash = hash * 31 + At(i).GetHashCode();
                }
            }

            return base.GetHashCode()
                ^ Length.GetHashCode()
                ^ hash;
        }

        #endregion


        #region Clearing

        public virtual void Clear()
        {
            for (var i = 0; i < Length; i++)
            {
                At(i, Zero);
            }
        }
        public virtual void Clear(int index, int count)
        {
            ValidateRange(index, count);

            for (var i = index; i < index + count; i++)
            {
                At(i, Zero);
            }
        }

        #endregion


        #region Copying

        // VECTOR COPY

        public void CopyTo(VectorStorage<T> target, ExistingData existingData = ExistingData.Clear)
        {
            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }

            if (ReferenceEquals(this, target))
            {
                return;
            }

            if (Length != target.Length)
            {
                throw new ArgumentException(Resources.Numerics.ArgumentVectorsSameLength, nameof(target));
            }

            CopyToUnchecked(target, existingData);
        }
        internal virtual void CopyToUnchecked(VectorStorage<T> target, ExistingData existingData)
        {
            for (int i = 0; i < Length; i++)
            {
                target[i] = this[i];
            }
        }

        // ROW COPY

        public void CopyToRow(MatrixStorage<T> target, int rowIndex, ExistingData existingData = ExistingData.Clear)
        {
            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }

            if (Length != target.ColumnCount)
            {
                throw new ArgumentException(Resources.Numerics.ArgumentVectorsSameLength, nameof(target));
            }

            ValidateRowRange(target, rowIndex);
            CopyToRowUnchecked(target, rowIndex, existingData);
        }
        internal virtual void CopyToRowUnchecked(MatrixStorage<T> target, int rowIndex, ExistingData existingData)
        {
            for (int j = 0; j < Length; j++)
            {
                target.At(rowIndex, j, At(j));
            }
        }

        // COLUMN COPY

        public void CopyToColumn(MatrixStorage<T> target, int columnIndex, ExistingData existingData = ExistingData.Clear)
        {
            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }

            if (Length != target.RowCount)
            {
                throw new ArgumentException(Resources.Numerics.ArgumentVectorsSameLength, nameof(target));
            }

            ValidateColumnRange(target, columnIndex);
            CopyToColumnUnchecked(target, columnIndex, existingData);
        }
        internal virtual void CopyToColumnUnchecked(MatrixStorage<T> target, int columnIndex, ExistingData existingData)
        {
            for (int i = 0; i < Length; i++)
            {
                target.At(i, columnIndex, At(i));
            }
        }

        // SUB-VECTOR COPY

        public void CopySubVectorTo(VectorStorage<T> target,
            int sourceIndex, int targetIndex, int count,
            ExistingData existingData = ExistingData.Clear)
        {
            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }

            if (count == 0)
            {
                return;
            }

            ValidateSubVectorRange(target, sourceIndex, targetIndex, count);
            CopySubVectorToUnchecked(target, sourceIndex, targetIndex, count, existingData);
        }
        internal virtual void CopySubVectorToUnchecked(VectorStorage<T> target,
            int sourceIndex, int targetIndex, int count, ExistingData existingData)
        {
            if (ReferenceEquals(this, target))
            {
                var tmp = new T[count];
                for (int i = 0; i < tmp.Length; i++)
                {
                    tmp[i] = At(i + sourceIndex);
                }
                for (int i = 0; i < tmp.Length; i++)
                {
                    At(i + targetIndex, tmp[i]);
                }

                return;
            }

            for (int i = sourceIndex, ii = targetIndex; i < sourceIndex + count; i++, ii++)
            {
                target.At(ii, At(i));
            }
        }
        
        // SUB-ROW COPY

        public void CopyToSubRow(MatrixStorage<T> target, int rowIndex,
            int sourceColumnIndex, int targetColumnIndex, int columnCount,
            ExistingData existingData = ExistingData.Clear)
        {
            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }

            if (columnCount == 0)
            {
                return;
            }

            ValidateSubRowRange(target, rowIndex, sourceColumnIndex, targetColumnIndex, columnCount);
            CopyToSubRowUnchecked(target, rowIndex, sourceColumnIndex, targetColumnIndex, columnCount, existingData);
        }
        internal virtual void CopyToSubRowUnchecked(MatrixStorage<T> target, int rowIndex,
            int sourceColumnIndex, int targetColumnIndex, int columnCount, ExistingData existingData)
        {
            for (int j = sourceColumnIndex, jj = targetColumnIndex; j < sourceColumnIndex + columnCount; j++, jj++)
            {
                target.At(rowIndex, jj, At(j));
            }
        }

        // SUB-COLUMN COPY

        public void CopyToSubColumn(MatrixStorage<T> target, int columnIndex,
            int sourceRowIndex, int targetRowIndex, int rowCount,
            ExistingData existingData = ExistingData.Clear)
        {
            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }

            if (rowCount == 0)
            {
                return;
            }

            ValidateSubColumnRange(target, columnIndex, sourceRowIndex, targetRowIndex, rowCount);
            CopyToSubColumnUnchecked(target, columnIndex, sourceRowIndex, targetRowIndex, rowCount, existingData);
        }
        internal virtual void CopyToSubColumnUnchecked(MatrixStorage<T> target, int columnIndex,
            int sourceRowIndex, int targetRowIndex, int rowCount, ExistingData existingData)
        {
            for (int i = sourceRowIndex, ii = targetRowIndex; i < sourceRowIndex + rowCount; i++, ii++)
            {
                target.At(ii, columnIndex, At(i));
            }
        }


        #endregion


        #region Enumerating

        public virtual IEnumerable<T> Enumerate()
        {
            for (var i = 0; i < Length; i++)
            {
                yield return At(i);
            }
        }

        public virtual IEnumerable<Tuple<int, T>> EnumerateIndexed()
        {
            for (var i = 0; i < Length; i++)
            {
                yield return new Tuple<int, T>(i, At(i));
            }
        }

        public virtual IEnumerable<T> EnumerateNonZero()
        {
            for (var i = 0; i < Length; i++)
            {
                var x = At(i);
                if (!Zero.Equals(x))
                {
                    yield return x;
                }
            }
        }

        public virtual IEnumerable<Tuple<int, T>> EnumerateNonZeroIndexed()
        {
            for (var i = 0; i < Length; i++)
            {
                var x = At(i);
                if (!Zero.Equals(x))
                {
                    yield return new Tuple<int, T>(i, x);
                }
            }
        }

        #endregion


        #region Extracting

        public virtual T[] ToArray()
        {
            var ret = new T[Length];
            for (int i = 0; i < ret.Length; i++)
            {
                ret[i] = At(i);
            }
            return ret;
        }

        #endregion


        #region Finding

        public virtual Tuple<int, T> Find(Func<T, bool> predicate, Zeros zeros)
        {
            for (int i = 0; i < Length; i++)
            {
                var item = At(i);
                if (predicate(item))
                {
                    return new Tuple<int, T>(i, item);
                }
            }
            return null;
        }

        public Tuple<int, T, TOther> Find2<TOther>(VectorStorage<TOther> other, Func<T, TOther, bool> predicate, Zeros zeros)
            where TOther : struct, IEquatable<TOther>, IFormattable
        {
            if (other == null)
            {
                throw new ArgumentNullException(nameof(other));
            }

            if (Length != other.Length)
            {
                throw new ArgumentException(Resources.Numerics.ArgumentVectorsSameLength, nameof(other));
            }

            return Find2Unchecked(other, predicate, zeros);
        }

        internal virtual Tuple<int, T, TOther> Find2Unchecked<TOther>(VectorStorage<TOther> other, Func<T, TOther, bool> predicate, Zeros zeros)
            where TOther : struct, IEquatable<TOther>, IFormattable
        {
            for (int i = 0; i < Length; i++)
            {
                var item = At(i);
                var otherItem = other.At(i);
                if (predicate(item, otherItem))
                {
                    return new Tuple<int, T, TOther>(i, item, otherItem);
                }
            }
            return null;
        }

        #endregion


        #region COMBINATORS - Maping

        /// <summary>
        /// 
        /// </summary>
        /// <param name="f">映射函数</param>
        /// <param name="zeros"></param>
        public virtual void MapInplace(Func<T, T> f, Zeros zeros)
        {
            for (int i = 0; i < Length; i++)
            {
                At(i, f(At(i)));
            }
        }

        public virtual void MapIndexedInplace(Func<int, T, T> fun, Zeros zeros)
        {
            for (int i = 0; i < Length; i++)
            {
                At(i, fun(i, At(i)));
            }
        }

        public void MapTo<TU>(VectorStorage<TU> target, Func<T, TU> f, Zeros zeros, ExistingData existingData)
            where TU : struct, IEquatable<TU>, IFormattable
        {
            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }

            if (Length != target.Length)
            {
                throw new ArgumentException(Resources.Numerics.ArgumentVectorsSameLength, nameof(target));
            }

            MapToUnchecked(target, f, zeros, existingData);
        }

        public void MapIndexedTo<TU>(VectorStorage<TU> target, Func<int, T, TU> f, Zeros zeros, ExistingData existingData)
            where TU : struct, IEquatable<TU>, IFormattable
        {
            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }

            if (Length != target.Length)
            {
                throw new ArgumentException(Resources.Numerics.ArgumentVectorsSameLength, nameof(target));
            }

            MapIndexedToUnchecked(target, f, zeros, existingData);
        }

        public void Map2To(VectorStorage<T> target, VectorStorage<T> other, Func<T, T, T> f, Zeros zeros, ExistingData existingData)
        {
            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }

            if (other == null)
            {
                throw new ArgumentNullException(nameof(other));
            }

            if (Length != target.Length)
            {
                throw new ArgumentException(Resources.Numerics.ArgumentVectorsSameLength, nameof(target));
            }

            if (Length != other.Length)
            {
                throw new ArgumentException(Resources.Numerics.ArgumentVectorsSameLength, nameof(other));
            }

            MapToUnchecked(target, other, f, zeros, existingData);
        }


        internal virtual void MapToUnchecked<TU>(VectorStorage<TU> target, Func<T, TU> f, Zeros zeros, ExistingData existingData)
            where TU : struct, IEquatable<TU>, IFormattable
        {
            for (int i = 0; i < Length; i++)
            {
                target.At(i, f(At(i)));
            }
        }
        internal virtual void MapToUnchecked(VectorStorage<T> target, VectorStorage<T> other, Func<T, T, T> fun, Zeros zeros, ExistingData existingData)
        {
            for (int i = 0; i < Length; i++)
            {
                target.At(i, fun(At(i), other.At(i)));
            }
        }
        internal virtual void MapIndexedToUnchecked<TU>(VectorStorage<TU> target, Func<int, T, TU> f, Zeros zeros, ExistingData existingData)
            where TU : struct, IEquatable<TU>, IFormattable
        {
            for (int i = 0; i < Length; i++)
            {
                target.At(i, f(i, At(i)));
            }
        }


        #endregion


        #region COMBINATORS - Folding

        public TState Fold2<TOther, TState>(VectorStorage<TOther> other, Func<TState, T, TOther, TState> f, TState state, Zeros zeros)
            where TOther : struct, IEquatable<TOther>, IFormattable
        {
            if (other == null)
            {
                throw new ArgumentNullException(nameof(other));
            }

            if (Length != other.Length)
            {
                throw new ArgumentException(Resources.Numerics.ArgumentVectorsSameLength, nameof(other));
            }

            return Fold2Unchecked(other, f, state, zeros);
        }

        internal virtual TState Fold2Unchecked<TOther, TState>(VectorStorage<TOther> other, Func<TState, T, TOther, TState> f, TState state, Zeros zeros)
            where TOther : struct, IEquatable<TOther>, IFormattable
        {
            for (int i = 0; i < Length; i++)
            {
                state = f(state, At(i), other.At(i));
            }

            return state;
        }

        #endregion



        #region Validations

        private void ValidateRange(int index)
        {
            if ((uint)index >= (uint)Length)
            {
                throw new ArgumentOutOfRangeException(nameof(index));
            }
        }

        private void ValidateRange(int index, int count)
        {
            if ((uint)index >= (uint)Length)
            {
                throw new ArgumentOutOfRangeException(nameof(index));
            }
            if ((uint)(index + count) >= (uint)Length)
            {
                throw new ArgumentOutOfRangeException(nameof(index));
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="target"></param>
        /// <param name="sourceIndex"></param>
        /// <param name="targetIndex"></param>
        /// <param name="count">数量</param>
        private void ValidateSubVectorRange(VectorStorage<T> target, int sourceIndex, int targetIndex, int count)
        {
            if (count < 1)
            {
                throw new ArgumentOutOfRangeException(nameof(count), Resources.Numerics.ArgumentMustBePositive);
            }

            // Verify Source
            //
            if ((uint)sourceIndex >= (uint)Length)
            {
                throw new ArgumentOutOfRangeException(nameof(sourceIndex));
            }

            var sourceMax = sourceIndex + count;
            if (sourceMax > Length)
            {
                throw new ArgumentOutOfRangeException(nameof(count));
            }

            // Verify Target
            //
            if ((uint)targetIndex >= (uint)target.Length)
            {
                throw new ArgumentOutOfRangeException(nameof(targetIndex));
            }

            var targetMax = targetIndex + count;
            if (targetMax > target.Length)
            {
                throw new ArgumentOutOfRangeException(nameof(count));
            }
        }

        private void ValidateRowRange(MatrixStorage<T> target, int rowIndex)
        {
            if ((uint)rowIndex >= (uint)target.RowCount)
            {
                throw new ArgumentOutOfRangeException(nameof(rowIndex));
            }

            if (target.ColumnCount != Length)
            {
                throw new ArgumentException(Resources.Numerics.ArgumentMatrixSameRowDimension, nameof(target));
            }
        }

        private void ValidateColumnRange(MatrixStorage<T> target, int columnIndex)
        {
            if ((uint)columnIndex >= (uint)target.ColumnCount)
            {
                throw new ArgumentOutOfRangeException(nameof(columnIndex));
            }

            if (target.RowCount != Length)
            {
                throw new ArgumentException(Resources.Numerics.ArgumentMatrixSameColumnDimension, nameof(target));
            }
        }

        private void ValidateSubRowRange(MatrixStorage<T> target, int rowIndex,
            int sourceColumnIndex, int targetColumnIndex, int columnCount)
        {
            if (columnCount < 1)
            {
                throw new ArgumentOutOfRangeException(nameof(columnCount), Resources.Numerics.ArgumentMustBePositive);
            }

            // Verify Source

            if ((uint)sourceColumnIndex >= (uint)Length)
            {
                throw new ArgumentOutOfRangeException(nameof(sourceColumnIndex));
            }

            if (sourceColumnIndex + columnCount > Length)
            {
                throw new ArgumentOutOfRangeException(nameof(columnCount));
            }

            // Verify Target

            if ((uint)rowIndex >= (uint)target.RowCount)
            {
                throw new ArgumentOutOfRangeException(nameof(rowIndex));
            }

            if ((uint)targetColumnIndex >= (uint)target.ColumnCount)
            {
                throw new ArgumentOutOfRangeException(nameof(targetColumnIndex));
            }

            if (targetColumnIndex + columnCount > target.ColumnCount)
            {
                throw new ArgumentOutOfRangeException(nameof(columnCount));
            }
        }

        private void ValidateSubColumnRange(MatrixStorage<T> target, int columnIndex,
            int sourceRowIndex, int targetRowIndex, int rowCount)
        {
            if (rowCount < 1)
            {
                throw new ArgumentOutOfRangeException(nameof(rowCount), Resources.Numerics.ArgumentMustBePositive);
            }

            // Verify Source

            if ((uint)sourceRowIndex >= (uint)Length)
            {
                throw new ArgumentOutOfRangeException(nameof(sourceRowIndex));
            }

            if (sourceRowIndex + rowCount > Length)
            {
                throw new ArgumentOutOfRangeException(nameof(rowCount));
            }

            // Verify Target

            if ((uint)columnIndex >= (uint)target.ColumnCount)
            {
                throw new ArgumentOutOfRangeException(nameof(columnIndex));
            }

            if ((uint)targetRowIndex >= (uint)target.RowCount)
            {
                throw new ArgumentOutOfRangeException(nameof(targetRowIndex));
            }

            if (targetRowIndex + rowCount > target.RowCount)
            {
                throw new ArgumentOutOfRangeException(nameof(rowCount));
            }
        }

        #endregion


        //}}@@@
    }


}
